package com.tiantian.system.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.annotation.SaIgnore;
import cn.hutool.core.util.RandomUtil;
import com.tiantian.common.core.constant.CacheConstants;
import com.tiantian.common.core.constant.Constants;
import com.tiantian.common.core.domain.ResponseResult;
import com.tiantian.common.log.annotation.Log;
import com.tiantian.common.log.enums.BusinessType;
import com.tiantian.common.ratelimiter.annotation.RateLimiter;
import com.tiantian.common.ratelimiter.enums.LimitType;
import com.tiantian.common.redis.utils.RedisUtils;
import com.tiantian.mail.config.properties.MailProperties;
import com.tiantian.mail.utils.MailUtils;
import jakarta.validation.constraints.NotBlank;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.Duration;


@Slf4j
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/system")
public class CaptchaController {

    @Value("${mail.brand}")
    private String brand;

    private final MailProperties mailProperties;

    /**
     * 邮箱验证码
     *
     * @param email 邮箱
     */
    @GetMapping("/captchaEmail")
    @SaIgnore
    @RateLimiter(time = 150, count = 2, limitType = LimitType.IP)
    @Log(businessType = BusinessType.CAPTCHA)
    public ResponseResult<Void> emailCode(@NotBlank(message = "邮箱不能为空") String email) {
        if (!mailProperties.getEnabled()) {
            return ResponseResult.fail("当前系统没有开启邮箱功能!");
        }
        String key = CacheConstants.CAPTCHA_CODE_KEY + email;
        String code = RandomUtil.randomNumbers(6);
        RedisUtils.setCacheObject(key, code, Duration.ofSeconds(Constants.CAPTCHA_EXPIRATION));
        try {
            // 异步发送邮件
            String subject = "注册验证码";
            String content = "您的正在进行注册，验证码为：" + code + "，请勿将验证码泄露于他人，本条验证码有效期为" + 5 + "分钟，请尽快填写。";
            MailUtils.sendText(email, subject, brand + content);
        } catch (Exception e) {
            log.error("验证码短信发送异常 => {}", e.getMessage());
            return ResponseResult.fail(e.getMessage());
        }
        return ResponseResult.ok();
    }

    @GetMapping("/updateEmail")
    @SaCheckLogin
    @RateLimiter(time = 30, count = 1, limitType = LimitType.IP)
    @Log(businessType = BusinessType.CAPTCHA)
    public ResponseResult<Void> getUpdateEmailCode(@NotBlank(message = "邮箱不能为空") String email) {
        if (!mailProperties.getEnabled()) {
            return ResponseResult.fail("当前系统没有开启邮箱功能!");
        }
        String key = CacheConstants.UPDATE_EMAIL_CAPTCHA_CODE_KEY + email;
        String code = RandomUtil.randomNumbers(6);
        RedisUtils.setCacheObject(key, code, Duration.ofSeconds(Constants.CAPTCHA_EXPIRATION));
        try {
            // 异步发送邮件
            String subject = "修改邮箱";
            String content = "您的正在修改邮箱, 验证码为：" + code + "，请勿将验证码泄露于他人，本条验证码有效期为" + 5 + "分钟，请尽快填写。";
            MailUtils.sendText(email, subject, brand + content);
        } catch (Exception e) {
            log.error("验证码短信发送异常 => {}", e.getMessage());
            return ResponseResult.fail(e.getMessage());
        }
        return ResponseResult.ok();
    }

}
